package com.woniuxy.microshoppingcartserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microshoppingcartserver.bean.Favorite;
import com.woniuxy.microshoppingcartserver.bean.ResponseMsg;
import com.woniuxy.microshoppingcartserver.service.FavoriteService;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@RequestMapping("/collect")
@RestController
public class FavoriteController {

    @Resource
    private FavoriteService favoriteServiceImpl;

    /**
     * 收藏商品
     * 判断是否已经收藏 如果没有就添加到收藏夹，如果已经收藏了就取消收藏
     * 一个商品被多少人收藏：用String显示 key（goodsId） value（用incre）自增，取消收藏用自减
     * hash存一个用户收藏的商品 key（userId） hk（goodsId） hv（goodsInfo对象）
     */
    @PostMapping("/add")
    public String addFavorite(Integer goodsId,@RequestParam("userId") String userId){
        int result = favoriteServiceImpl.addFavorite(goodsId,userId);
        if (result == 0){
            return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("已取消收藏").build());
        }else{
            return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("收藏成功").build());
        }
    }

    /**
     * 查看收藏夹
     */
    @GetMapping("/look")
    public String lookCollection(Integer start, Integer end,@RequestParam("userId") String userId){
        List<Favorite> collcetions = favoriteServiceImpl.lookFavotite(start, end,userId);
        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("收藏成功").data(collcetions).build());
    }

    @DeleteMapping("/{goodsId}")
    public String deleteFavorite(@PathVariable("goodsId") Integer goodsId,@RequestParam("userId") String userId){
        favoriteServiceImpl.deleteFavorite(goodsId,userId);
        return JSONObject.toJSONString(ResponseMsg.builder().code(200).msg("已取消收藏").build());
    }
}
